package javaweb.interceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import javaweb.util.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;



@Slf4j
/*@Component*/
public class TokenInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
            //获取请求的url路径
            String url = request.getRequestURI(); // /emp/login

            //1.校验路径中是否包含login，如果包含，说明是登录操作，放行
            if(url.contains("/login")){
                log.info("登录操作，放行");
                return true;
            }

            //2.从请求头中获取token
            String token = request.getHeader("token");

            //3.检验token是否存在，不存在则返回401
            if((token == null) || (token.isEmpty())){
                log.info("令牌不存在，返回401状态码");
                response.setStatus(401);
                return false;
            }

            //4.解析token，如果解析失败则返回401
            try {
                JwtUtils.parseJWT(token);
            } catch (Exception e) {
                e.printStackTrace();
                log.info("令牌解析失败，返回401状态码");
                response.setStatus(401);
                return false;
            }

            //5.放行
            log.info("令牌合法，放行");
            return true;
    }
}
